const app = getApp();
import { queryAll } from '../../api/coupon.js';
import { add } from '../../api/userCoupon.js';

Page({
  data: {
    points: 0, 
    exchangeableCoupons: []
  },

  onLoad(options) {
    // 接收从wallet页面传递的积分
    this.setData({ points: options.points || 0 });
    this.loadData();
  },

  navToWallet() {
    wx.redirectTo({ url: '/pages/wallet/wallet' });
  },

  async loadData() {
      const res = await queryAll();
      if (res.code === 200 && Array.isArray(res.data)) {
        this.setData({ exchangeableCoupons: res.data });
      } else {
        wx.showToast({ title: '优惠券列表加载失败', icon: 'none' });
      }
  },

  async handleExchange(e) {
    const couponId = e.currentTarget.dataset.couponid;
    const { points, exchangeableCoupons } = this.data;
    const coupon = exchangeableCoupons.find(item => item.id === couponId);

    if (points < coupon.requiredPoints) {
      wx.showToast({ title: '积分不足，无法兑换！', icon: 'none' });
      return;
    }

    try {
      await new Promise((resolve, reject) => {
        wx.showModal({
          title: '兑换确认',
          content: `确定要用 ${coupon.requiredPoints} 积分兑换【${coupon.name}】吗？`,
          confirmText: '确定',
          cancelText: '取消',
          success: (res) => res.confirm ? resolve() : reject('cancel'),
          fail: () => reject('modalError')
        });
      });

      const res = await add({ id: couponId });
      if (res.code === 200) {
        wx.showToast({ title: '兑换成功！优惠券已放入您的卡包', icon: 'success' });
        setTimeout(() => this.navToWallet(), 1500);
      } else {
        wx.showToast({ title: res.msg || '兑换失败，请稍后重试', icon: 'none' });
      }
    } catch (error) {
      if (error === 'cancel') {
        wx.showToast({ title: '已取消兑换', icon: 'none' });
      } else {
        wx.showToast({ title: '网络异常，兑换失败', icon: 'none' });
      }
    }
  }
});